<template>
  <div>
    <el-upload
      list-type="picture-card"
      :limit="1"
      action="#"
      :on-preview="preview"
      :on-remove="handleRemove"
      :on-change="changeFile"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :http-request="upload"
      :class="{ disabled: fileComputed }"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-progress
      v-if="showPercent"
      style="width: 180px"
      :percentage="percent"
    ></el-progress>
    <el-dialog :visible.sync="showDialog" title="图片预览">
      <img :src="imgUrl" alt="" style="width: 100%" />
    </el-dialog>
  </div>
</template>
<script>
import COS from "cos-js-sdk-v5"; //引入腾讯云cos包
// 实例化cos对象
const cos = new COS({
  SecretId: "AKID3wZv0oLaZHislOjob9QP77sMZVBaiY8R", //身份识别ID
  SecretKey: "3pLbbKmxrUqvjGVUCdnfHcfRwB8oEMDn", //身份识别密钥
});
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      fileList: [],
      showDialog: false,
      imgUrl: "",
      currentFileUid: null, //记录当前上传的图片文件
      percent: 0,
      showPercent: false,
    };
  },
  computed: {
    fileComputed() {
      return this.fileList.length === 1;
    },
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    preview(file) {
      // console.log(file);
      this.showDialog = true;
      this.imgUrl = file.url;
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter((item) => item.uid !== file.uid);
    },
    // 修改文件时触发
    // 此时可以用fileList 因为该方法会进来很多遍 不能每次都去push
    // fileList因为fileList参数是当前传进来的最新参数 我们只需要将其转化成数组即可 需要转化成一个新的数组
    // [] => [...fileList] [] => fileList.map()
    // 上传成功之后 还会进来 需要实现上传代码的逻辑 这里才会成功
    changeFile(file, fileList) {
      console.log(fileList.length);
      this.fileList = fileList.map((item) => item);
    },
    beforeUpload(file) {
      // console.log(file);
      const typeImg = ["image/jpeg", "image/jpg", "image/png", "image/gif"];
      if (!typeImg.includes(file.type)) {
        this.$message.error("上传图片只能是 JPG、GIF、BMP、PNG 格式!");
        return false;
      }
      const maxSize = 15 * 1024 * 1024;
      if (file.size > maxSize) {
        this.$message.error("图片大小最大不能超过5M");
        return false;
      }
      // console.log(file);
      this.currentFileUid = file.uid;
      this.showPercent = true;
      return true;
    },
    upload(params) {
      if (params.file) {
        // 执行上传操作
        cos.putObject(
          {
            Bucket: "lucky-1253946584", // 存储桶
            Region: "ap-guangzhou", // 地域
            Key: params.file.name, // 文件名
            Body: params.file, // 要上传的文件对象
            StorageClass: "STANDARD", // 上传的模式类型 直接默认 标准模式即可
            // 上传到腾讯云 =》 哪个存储桶 哪个地域的存储桶 文件  格式  名称 回调
            onProgress: (params) => {
              console.log(params);
              this.percent = params.percent * 100;
            },
          },
          (err, data) => {
            // data返回数据之后 应该如何处理
            console.log(err || data);
            if (!err && data.statusCode === 200) {
              // 此时说明上传文件成功
              this.fileList = this.fileList.map((item) => {
                if (item.uid === this.currentFileUid) {
                  return { url: "http://" + data.Location, upload: true };
                }
                return item;
              });
              setTimeout(() => {
                this.showPercent = false;
                this.percent = 0;
              }, 1000);
            }
          }
        );
      }
    },
  },
};
</script>
<style>
.disabled .el-upload--picture-card {
  display: none;
}
</style>